import { DeploymentExecutorSchema } from './schema';
import { ExecutorContext } from '@nrwl/devkit';
import {
  cpSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  rmSync,
  writeFileSync,
} from 'fs';
import { listTags } from 'isomorphic-git';
import * as fs from 'fs';
import { parse, stringify } from 'yaml';

const DEPLOYMENT_DIR = 'deployment';

export default async function runExecutor(
  options: DeploymentExecutorSchema,
  context: ExecutorContext
) {
  console.log('Cleaning up Deployment...');
  const deploymentDirContents = readdirSync(DEPLOYMENT_DIR);

  const pathToDeployment = `${DEPLOYMENT_DIR}/${context.projectName}`;

  if (deploymentDirContents.find((name) => name === context.projectName)) {
    rmSync(pathToDeployment, { recursive: true });
  } else {
    console.log('nothing to clean up');
  }

  console.log('\n');
  console.log('Creating new Deployment');
  mkdirSync(pathToDeployment);

  console.log('copying Dockerfile');
  cpSync(options.dockerfile, `${pathToDeployment}/Dockerfile`);

  console.log('copying HELM-chart');
  cpSync(options.helmChart, `${pathToDeployment}/chart`, { recursive: true });

  const allTags = await listTags({ fs, dir: '.' });
  let currentTag = `${context.projectName}-0.0.0`;

  for (const tag of allTags) {
    if (tag.startsWith(context.projectName)) {
      currentTag = tag;
    }
  }

  const currentVersion = currentTag
    .replace(context.projectName, '')
    .substring(1);
  console.log(`Current version is ${currentVersion}`);

  writeFileSync(`${pathToDeployment}/version`, currentVersion);

  const valueDoc = parse(
    readFileSync(`${pathToDeployment}/chart/Chart.yaml`, { encoding: 'utf8' })
  );
  valueDoc.version = currentVersion;
  writeFileSync(`${pathToDeployment}/chart/Chart.yaml`, stringify(valueDoc), {
    encoding: 'utf8',
  });

  console.log('\n');
  console.log('done');

  return {
    success: true,
  };
}
